import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<any>({})
  const setting = ref<any>({})

  async function getUserInfo() {
    const { Code, Data } = await useRequest.post('/GetUserInfo')
    if (Code === 0) {
      updateUserInfo(Data?.user ?? Data ?? {})
    } else {
      clearUserInfo()
    }
  }

  async function getServerSetting() {
    const { Code, Data } = await useRequest.post('/ServerSetting')
    if (Code === 0) {
      setting.value = Data
    }
  }

  function updateUserInfo(value: any) {
    const userLocalStore = JSON.parse(localStorage.getItem('userinfo') ?? `{}`)
    Object.assign(userInfo.value, userLocalStore)
    Object.assign(userInfo.value, value)
    localStorage.setItem('userinfo', JSON.stringify(userInfo.value))
  }

  function clearUserInfo() {
    userInfo.value = {}
    localStorage.setItem('userinfo', '{}')
  }

  return {
    setting,
    userInfo,
    getUserInfo,
    clearUserInfo,
    updateUserInfo,
    getServerSetting,
  }
})

export const useMovieStore = defineStore('movie', () => {
  const movieList = ref<any[]>([])
  const movieIndex = ref(0)

  function updateMovieList(value: any) {
    movieList.value = value
  }

  return {
    movieIndex,
    movieList,
    updateMovieList,
  }
})
